package service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import service.interf.IBaseDataService;

import common.impl.JSONExt;
import common.impl.SpringContextUtil;
import common.impl.exception.ServiceException;
import common.interf.IDataHandle;
import common.interf.IMyDateHandle;

import dao.interf.IBaseDAO;
import dao.pojo.BasePojo;

/**
 * 基础数据业务实现
 * 
 * @author fieldyang
 * @since 2012-06-24
 * @version 1.0
 */
@SuppressWarnings("unchecked")
public class BaseDataServiceImpl implements IBaseDataService {
	private final String ENTITYPATH = "dao.pojo.";
	private final String INCLUDECLASS = "java.lang.Byte,java.lang.Double,java.lang.Float,java.lang.Long,java.lang.Integer,"
			+ "java.lang.Number,java.math.BigDecimal,java.lang.Short,java.lang.String,java.lang.Boolean,java.sql.Timestamp";

	private IDataHandle dataHandle;
	private String realPath;
	public IMyDateHandle myDateHandle;

	public void setDataHandle(IDataHandle dataHandle) {
		this.dataHandle = dataHandle;
	}

	public String getRealPath() {
		return realPath;
	}

	public void setMyDateHandle(IMyDateHandle myDateHandle) {
		this.myDateHandle = myDateHandle;
	}

	/**
	 * 获取查询结果字符串
	 * 
	 * @param entityName
	 *            实体名(和dao.pojo中定义一样，包含大小写)
	 * @param fieldStr
	 *            要查询的字段,以“,”分隔,基于外键的关系,用对象方式,如company.companyName,
	 *            如果查询所有常规(非对象、集合类型,参考INCLUDECLASS)字段,用*代替, 如
	 *            *,company.companyName,category.categoryName。默认为 *,
	 *            如果需要数据格式转换，在字段后面加 (:date)表示转换为标准日期
	 *            格式(2012-03-21)，(expName:date) 表示输出字段名为expName,格式为date,
	 *            目前格式转换只支持 date 例:xxx.x(x1),[distinct]yyy.y(y1),*,表示 yyy.y
	 *            修饰符为distinct,输出为y1。
	 * @param dataType
	 *            返回字符串类型 json, xml。默认为 json
	 * @param isGetTotal
	 *            是否获取记录数
	 * @param pNames
	 *            条件名数组
	 * @param pValues
	 *            条件值数组
	 * @param logic
	 *            逻辑 and or 或括号
	 * @param relation
	 *            条件名和值关系数组
	 * @param pageno
	 *            页号
	 * @param pagesize
	 *            页面大小
	 * @param sort
	 *            可以为空。排序条件,该值为数组,第一个为字段名,第二个排序方法(asc或desc),排序方法可以为空,
	 *            默认为asc(升序)。 如 commodityId,categoryId asc,desc。
	 * @return 结果字符串
	 * @throws Exception
	 * 
	 */
	public String findByProperty(String entityName, String fieldStr,
			String dataType, boolean isGetTotal, String[] pNames,
			Object[] pValues, String[] logic, String[] relation,
			Integer pageno, Integer pagesize, String... sort) throws Exception {
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		int start = 0;
		String rule = null;
		if (StringUtils.isEmpty(fieldStr))
			fieldStr = "*";
		if (StringUtils.isEmpty(dataType))
			dataType = "json";

		String[] fields = fieldStr.split(",");
		List<MyField> lstField = new ArrayList<MyField>();
		List<String> fieldArr = new ArrayList<String>();
		Boolean hasAll = false;
		for (int i = 0, len = fields.length; i < len; i++) {
			if ("*".equals(fields[i])) {
				hasAll = true;
			} else {
				MyField field = new MyField();
				int ind1, ind2, ind3, ind4, ind5;

				ind1 = fields[i].indexOf("[");
				ind2 = fields[i].indexOf("]");
				if (ind1 >= 0 && ind2 > ind1 + 1) { // modifier
					field.modifier = fields[i].substring(ind1 + 1, ind2);
				}

				ind3 = fields[i].indexOf("(");
				ind4 = fields[i].indexOf(")");
				if (ind3 >= 0 && ind4 > ind3 + 1) { // exportName or format
					String tn = fields[i].substring(ind3 + 1, ind4);
					ind5 = tn.indexOf(":");
					if (ind5 == -1) {
						field.exportName = tn;
					} else {
						field.format = tn.substring(ind5 + 1);
						if (ind3 > ind1 + 2) { // 有输出字段
							field.exportName = tn.substring(0, ind5);
						}
					}
				}
				if (ind2 > 0) {
					if (ind3 > 0)
						field.fieldName = fields[i].substring(ind2 + 1, ind3);
					else
						field.fieldName = fields[i].substring(ind2 + 1);
				} else if (ind3 > 0) {
					field.fieldName = fields[i].substring(0, ind3);
				} else {
					field.fieldName = fields[i];
				}
				lstField.add(field);
				fieldArr.add(field.fieldName);
			}
		}
		// 替换*为所有基本字段
		if (hasAll) {
			try {
				Field[] decFields = Class.forName(ENTITYPATH + entityName)
						.getDeclaredFields();
				for (int i = 0, len = decFields.length; i < len; i++) {
					String fn = decFields[i].getName();
					// 重复字段和 复杂字段 不添加
					if (fieldArr.contains(fn)
							|| !INCLUDECLASS.contains(decFields[i].getType()
									.getName()))
						continue;
					MyField field = new MyField();
					field.fieldName = fn;
					lstField.add(field);
					fieldArr.add(fn);
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		// 构造返回字段数组
		StringBuffer fieldSb = new StringBuffer();
		int len = lstField.size();
		String[] modifiers = new String[len];
		String[] formats = new String[len];
		String[] fieldRet = new String[len];

		for (int i = 0; i < len; i++) {
			MyField f = lstField.get(i);
			if (StringUtils.isEmpty(f.modifier))
				modifiers[i] = "";
			else
				modifiers[i] = f.modifier;

			if (StringUtils.isEmpty(f.format))
				formats[i] = null;
			else
				formats[i] = f.format;

			fieldSb.append(f.fieldName);
			if (!StringUtils.isEmpty(f.exportName)) {
				fieldSb.append(" as ");
				fieldSb.append(f.exportName);
				fieldRet[i] = f.exportName;
			} else {
				String fn = f.fieldName;
				fieldRet[i] = fn;
			}

			if (i < len - 1)
				fieldSb.append(",");
		}

		// 构建排序规则
		StringBuffer ruleBf = null;
		if (null != sort && sort.length > 0) {
			ruleBf = new StringBuffer(" order by ");
			String[] sortFields = sort[0].split(",");
			len = sortFields.length;
			String[] sortType = null;
			if (sort.length > 1) {
				sortType = sort[1].split(",");
			} else { // 如果排序值为空，默认为升序
				sortType = new String[len];
				for (int i = 0; i < len; i++)
					sortType[i] = "asc";
			}
			for (int i = 0; i < len; i++) {
				ruleBf.append("model." + sortFields[i] + " " + sortType[i]);
				if (i != len - 1)
					ruleBf.append(",");
			}
			rule = ruleBf.toString();
		}

		Long total = null;
		if (isGetTotal) { // 获取记录数
			total = dao.getPropertiesCount(pNames, pValues, logic, relation,
					rule);
		}
		// 生成分页数据
		if (null != pageno && pageno > 0)
			start = (pageno - 1) * pagesize;

		List lst = dao.findByPropertiesRule(fieldSb.toString(), pNames,
				pValues, logic, relation, rule, start, pagesize, modifiers);

		if (null != lst) {
			return dataHandle.transferData(fieldRet, formats, lst, total,
					dataType);
		}
		return null;
	}

	public String findByPropertyList(String entityName, String fieldStr,
			String dataType, boolean isGetTotal, List<String> pNameL,
			List<Object> pValueL, List<String> logicL, List<String> relationL,
			Integer pageno, Integer pagesize, String... sort) throws Exception {
		String[] pNames = null;
		Object[] pValues = null;
		String[] relations = null;
		String[] logics = null;
		if (null != pNameL && !pNameL.isEmpty()) {
			int size = pNameL.size();
			pNames = new String[size];
			pValues = new Object[size];
			pNames = pNameL.toArray(pNames);
			pValues = pValueL.toArray(pValues);
			if(null != relationL) {
				relations = new String[size];
				relations = relationL.toArray(relations);
			}
		}
		if (null != logicL && !logicL.isEmpty()) {
			logics = new String[logicL.size()];
			logics = logicL.toArray(logics);
		}
		return findByProperty(entityName, fieldStr, dataType, isGetTotal,
				pNames, pValues, logics, relations, pageno, pagesize, sort);
	}

	/**
	 * 获取对象列表
	 * 
	 * @param entityName
	 * @param pNames
	 * @param pValues
	 * @return
	 * @throws Exception
	 */
	public List findByProperty(String entityName, String[] pNames,
			Object[] pValues) throws Exception {
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		return dao.findByProperties(pNames, pValues);
	}

	/**
	 * 批量保存数据
	 * 
	 * @param datas
	 *            {adds:[{model,model}],edits:[{model,model}],removes:[{model,model
	 *            }]}
	 * @return 成功或失败
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws ClassNotFoundException
	 */
	public Boolean batchSave(String entityName, String datas,
			Map<String, Object> extraParams) throws SecurityException,
			NoSuchMethodException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException,
			ClassNotFoundException {
		if (null == datas || StringUtils.isEmpty(datas))
			return true;

		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		Class clazz = Class.forName(ENTITYPATH + entityName);

		JSONObject jwhole = JSONObject.fromObject(datas);

		// 附加参数初始化，减少循环计算
		String[] extArr = extraParams.keySet().toArray(new String[0]);
		Integer extLen = extArr.length;

		// 删除记录
		if (jwhole.containsKey("deletes")) {
			JSONArray ja = jwhole.getJSONArray("deletes");
			for (int i = 0, len = ja.size(); i < len; i++) {
				JSONObject jobj = ja.getJSONObject(i);
				if (null != jobj) {
					dao.delete(JSONExt.toBean(jobj, clazz));
				}
			}
		}
		// 添加记录
		if (jwhole.containsKey("adds")) {
			JSONArray ja = jwhole.getJSONArray("adds");
			for (int i = 0, len = ja.size(); i < len; i++) {
				JSONObject jobj = ja.getJSONObject(i);
				if (null != jobj) {
					// 增加附加参数
					if (extLen > 0) {
						for (int j = 0; j < extLen; j++) {
							jobj.put(extArr[j], extraParams.get(extArr[j]));
						}
					}
					BasePojo bp = (BasePojo) JSONExt.toBean(jobj, clazz);
					if (null == bp.getEntityId()) {
						try {
							addRecord(bp);
						} catch (Exception e) {
						}
					}
				}
			}
		}
		// 修改记录
		if (jwhole.containsKey("edits")) {
			JSONArray ja = jwhole.getJSONArray("edits");
			for (int i = 0, len = ja.size(); i < len; i++) {
				JSONObject jobj = ja.getJSONObject(i);
				if (null != jobj) {
					// 增加附加参数
					if (extLen > 0) {
						for (int j = 0; j < extLen; j++) {
							jobj.put(extArr[j], extraParams.get(extArr[j]));
						}
					}

					try {
						editRecord(JSONExt.toBean(jobj, clazz));
					} catch (Exception e) {
					}
				}
			}
		}

		return true;
	}

	/**
	 * 批量保存数据
	 * 
	 * @param datas
	 *            json对象{adds:[{model,model}],edits:[{model,model}],removes:[{model
	 *            ,model}]}
	 * @return 成功或失败
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws ClassNotFoundException
	 */
	public Boolean batchSave(String entityName, JSONObject datas,
			Map<String, Object> extraParams) throws SecurityException,
			NoSuchMethodException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException,
			ClassNotFoundException {
		if (null == datas)
			return true;

		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		Class clazz = Class.forName(ENTITYPATH + entityName);

		JSONObject jwhole = datas;

		// 附加参数初始化，减少循环计算
		String[] extArr = extraParams.keySet().toArray(new String[0]);
		Integer extLen = extArr.length;

		// 删除记录
		if (jwhole.containsKey("deletes")) {
			JSONArray ja = jwhole.getJSONArray("deletes");
			for (int i = 0, len = ja.size(); i < len; i++) {
				JSONObject jobj = ja.getJSONObject(i);
				if (null != jobj) {
					dao.delete(JSONExt.toBean(jobj, clazz));
				}
			}
		}
		// 添加记录
		if (jwhole.containsKey("adds")) {
			JSONArray ja = jwhole.getJSONArray("adds");
			for (int i = 0, len = ja.size(); i < len; i++) {
				JSONObject jobj = ja.getJSONObject(i);
				if (null != jobj) {
					// 增加附加参数
					if (extLen > 0) {
						for (int j = 0; j < extLen; j++) {
							jobj.put(extArr[j], extraParams.get(extArr[j]));
						}
					}
					BasePojo bp = (BasePojo) JSONExt.toBean(jobj, clazz);
					if (null == bp.getEntityId()) {
						try {
							addRecord(bp);
						} catch (Exception e) {
						}
					}
				}
			}
		}
		// 修改记录
		if (jwhole.containsKey("edits")) {
			JSONArray ja = jwhole.getJSONArray("edits");
			for (int i = 0, len = ja.size(); i < len; i++) {
				JSONObject jobj = ja.getJSONObject(i);
				if (null != jobj) {
					// 增加附加参数
					if (extLen > 0) {
						for (int j = 0; j < extLen; j++) {
							jobj.put(extArr[j], extraParams.get(extArr[j]));
						}
					}

					try {
						editRecord(JSONExt.toBean(jobj, clazz));
					} catch (Exception e) {
					}
				}
			}
		}
		return true;
	}

	/**
	 * 添加单条记录
	 * 
	 * @param entity
	 *            :要操作的实体
	 * @return: entity
	 * @throws ClassNotFoundException
	 */
	public Object addRecord(Object entity) throws Exception {
		if (null == entity)
			return null;
		Class cls = entity.getClass();
		String entName = getEntityName(entity);
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entName + "DAO");
		Field[] fields = cls.getDeclaredFields();
		for (int i = 0, len = fields.length; i < len; i++) {
			Field field = fields[i];
			String tn = field.getType().getName();
			// 处理外键 对象
			if (!INCLUDECLASS.contains(tn) && !tn.contains("Set")
					&& fields[i].getModifiers() == 2) {
				String fn = field.getName();
				fn = fn.substring(0, 1).toUpperCase() + fn.substring(1);
				Method method = cls.getMethod("get" + fn);
				BasePojo bp = (BasePojo) method.invoke(entity);
				entName = tn.substring(tn.lastIndexOf(".") + 1);
				IBaseDAO dao1 = (IBaseDAO) SpringContextUtil.getBean(entName
						+ "DAO");
				if (null != bp) {
					method = cls.getMethod("set" + fn, bp.getClass());
					if (null != bp.getEntityId()) { // 通过id查找实体
						bp = (BasePojo) dao1.findById(bp.getEntityId());
					} else {
						bp = null;
					}
					method.invoke(entity, new Object[] { bp });
				}
			}
		}
		dao.save(entity);
		return entity;
	}

	/**
	 * 编辑单条记录
	 * 
	 * @param entity
	 *            :要操作的实体
	 * @return: entity
	 * @throws ClassNotFoundException
	 */
	public Object editRecord(Object entity) throws Exception {
		if (null == entity)
			return null;
		Class cls = entity.getClass();
		String entName = getEntityName(entity);
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entName + "DAO");
		Field[] fields = cls.getDeclaredFields();
		for (int i = 0, len = fields.length; i < len; i++) {
			Field field = fields[i];
			String tn = field.getType().getName();
			// 处理外键 对象
			if (!INCLUDECLASS.contains(tn) && !tn.contains("Set")
					&& fields[i].getModifiers() == 2) {
				String fn = field.getName();
				fn = fn.substring(0, 1).toUpperCase() + fn.substring(1);
				Method method = cls.getMethod("get" + fn);
				BasePojo bp = (BasePojo) method.invoke(entity);
				entName = tn.substring(tn.lastIndexOf(".") + 1);
				IBaseDAO dao1 = (IBaseDAO) SpringContextUtil.getBean(entName
						+ "DAO");
				if (null != bp) {
					method = cls.getMethod("set" + fn, bp.getClass());
					if (null != bp.getEntityId()) { // 通过id查找实体
						bp = (BasePojo) dao1.findById(bp.getEntityId());
					} else {
						bp = null;
					}
					method.invoke(entity, new Object[] { bp });
				}
			}
		}
		dao.update(entity);
		return entity;
	}

	/**
	 * 删除单条记录
	 * 
	 * @param entityName
	 *            :实体名
	 * @param id
	 *            :要操作的实体编号
	 * @return: entity
	 * @throws ClassNotFoundException
	 */
	public Object delById(String entityName, Object id)
			throws ClassNotFoundException {
		if (null == id)
			return null;
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		dao.deleteById(id);
		return id;
	}

	/**
	 * 删除单条记录
	 * 
	 * @param entityName
	 *            :实体名
	 * @param entity
	 *            :要操作的实体
	 * @return: entity
	 * @throws ClassNotFoundException
	 */
	public Object delRecord(String entityName, Object entity)
			throws ClassNotFoundException {
		if (null == entity)
			return null;
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		dao.delete(entity);
		return entity;
	}

	/**
	 * 删除单条记录
	 * 
	 * @param entity
	 *            :要操作的实体
	 * @return: entity
	 * @throws ClassNotFoundException
	 */
	public Object delRecord(BasePojo entity) throws ClassNotFoundException {
		if (null == entity)
			return null;
		String entityName = getEntityName(entity);
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		dao.deleteById(entity.getEntityId());
		return entity;
	}

	/**
	 * 删除多条记录
	 * 
	 * @param entityName
	 *            :实体名
	 * @param ids
	 *            :id串
	 * @return: true
	 * @throws ClassNotFoundException
	 */
	public Boolean delByIds(String entityName, String idName, String ids)
			throws ClassNotFoundException {
		if (StringUtils.isEmpty(ids))
			return true;
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		String[] idArr = ids.split(",");
		if (null == idArr)
			return true;

		List<Object> lst = new ArrayList<Object>();
		for (int i = 0, len = idArr.length; i < len; i++)
			lst.add(idArr[i]);
		dao.deleteByProperties(new String[] { idName }, new Object[] { lst },
				new String[] { "in" });
		return true;
	}

	/**
	 * 通过entity 获取name
	 * 
	 * @param entity
	 *            :要查询的entity
	 * @return entityName
	 */
	private String getEntityName(Object entity) {
		Class cls = entity.getClass();
		String cn = cls.getName();
		String entName = cn.substring(cn.lastIndexOf(".") + 1);
		return entName;
	}

	private class MyField {
		private String fieldName = null;
		private String modifier = null;
		private String exportName = null;
		private String format = null;

		public String getFieldName() {
			return fieldName;
		}

		public void setFieldName(String fieldName) {
			this.fieldName = fieldName;
		}

		public String getModifier() {
			return modifier;
		}

		public void setModifier(String modifier) {
			this.modifier = modifier;
		}

		public String getExportName() {
			return exportName;
		}

		public void setExportName(String exportName) {
			this.exportName = exportName;
		}

		public String getFormat() {
			return format;
		}

		public void setFormat(String format) {
			this.format = format;
		}
	}

	/**
	 * 获取单个信息结果字符串
	 * 
	 * @param entityName
	 *            实体名(和dao.pojo中定义一样，包含大小写)
	 * @param fieldStr要查询的字段
	 *            ,以“,”分隔,基于外键的关系,用对象方式,如company.companyName,
	 *            如果查询所有常规(非对象、集合类型,参考INCLUDECLASS)字段,用*代替, 如
	 *            *,company.companyName,category.categoryName。默认为 *,
	 *            如果需要数据格式转换，在字段后面加 (:date)表示转换为标准日期
	 *            格式(2012-03-21)，(expName:date) 表示输出字段名为expName,格式为date,
	 *            目前格式转换只支持 date 例:xxx.x(x1),[distinct]yyy.y(y1),*,表示 yyy.y
	 *            修饰符为distinct,输出为y1。
	 * @param dataType返回字符串类型
	 *            json, xml。默认为 json
	 * @param idName
	 *            主键名
	 * @param id
	 *            主键值
	 * @return 结果字符串
	 * @throws Exception
	 * 
	 */
	public String findById(String entityName, String fieldStr, String dataType,
			String idName, Object id) throws Exception {
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		if (StringUtils.isEmpty(fieldStr))
			fieldStr = "*";
		if (StringUtils.isEmpty(dataType))
			dataType = "json";

		String[] fields = fieldStr.split(",");
		List<MyField> lstField = new ArrayList<MyField>();
		List<String> fieldArr = new ArrayList<String>();
		Boolean hasAll = false;
		for (int i = 0, len = fields.length; i < len; i++) {
			if ("*".equals(fields[i])) {
				hasAll = true;
			} else {
				MyField field = new MyField();
				int ind1, ind2, ind3, ind4, ind5;

				ind1 = fields[i].indexOf("[");
				ind2 = fields[i].indexOf("]");
				if (ind1 >= 0 && ind2 > ind1 + 1) { // modifier
					field.modifier = fields[i].substring(ind1 + 1, ind2);
				}

				ind3 = fields[i].indexOf("(");
				ind4 = fields[i].indexOf(")");
				if (ind3 >= 0 && ind4 > ind3 + 1) { // exportName or format
					String tn = fields[i].substring(ind3 + 1, ind4);
					ind5 = tn.indexOf(":");
					if (ind5 == -1) {
						field.exportName = tn;
					} else {
						field.format = tn.substring(ind5 + 1);
						if (ind3 > ind1 + 2) { // 有输出字段
							field.exportName = tn.substring(0, ind5);
						}
					}
				}
				if (ind2 > 0) {
					if (ind3 > 0)
						field.fieldName = fields[i].substring(ind2 + 1, ind3);
					else
						field.fieldName = fields[i].substring(ind2 + 1);
				} else if (ind3 > 0) {
					field.fieldName = fields[i].substring(0, ind3);
				} else {
					field.fieldName = fields[i];
				}
				lstField.add(field);
				fieldArr.add(field.fieldName);
			}
		}
		// 替换*为所有基本字段
		if (hasAll) {
			try {
				Field[] decFields = Class.forName(ENTITYPATH + entityName)
						.getDeclaredFields();
				for (int i = 0, len = decFields.length; i < len; i++) {
					String fn = decFields[i].getName();
					// 重复字段和 复杂字段 不添加
					if (fieldArr.contains(fn)
							|| !INCLUDECLASS.contains(decFields[i].getType()
									.getName()))
						continue;
					MyField field = new MyField();
					field.fieldName = fn;
					lstField.add(field);
					fieldArr.add(fn);
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		// 构造返回字段数组
		StringBuffer fieldSb = new StringBuffer();
		int len = lstField.size();
		String[] modifiers = new String[len];
		String[] formats = new String[len];
		String[] fieldRet = new String[len];

		for (int i = 0; i < len; i++) {
			MyField f = lstField.get(i);
			if (StringUtils.isEmpty(f.modifier))
				modifiers[i] = "";
			else
				modifiers[i] = f.modifier;

			if (StringUtils.isEmpty(f.format))
				formats[i] = null;
			else
				formats[i] = f.format;

			fieldSb.append(f.fieldName);
			if (!StringUtils.isEmpty(f.exportName)) {
				fieldSb.append(" as ");
				fieldSb.append(f.exportName);
				fieldRet[i] = f.exportName;
			} else {
				String fn = f.fieldName;
				fieldRet[i] = fn;
			}

			if (i < len - 1)
				fieldSb.append(",");
		}
		try {
			List lst = dao.findByPropertiesRule(fieldSb.toString(),
					new String[] { idName }, new Object[] { id }, null, null,
					null, 0, 0, modifiers);
			Object o = lst.get(0);
			len = fieldRet.length;
			Object[] rcd;
			if (len > 1)
				rcd = (Object[]) o;
			else
				// 返回单对象处理
				rcd = new Object[] { o };
			JSONObject jobj = new JSONObject();
			for (int i = 0; i < len; i++) {
				Object fv = rcd[i];
				if (null == fv)
					continue;
				if (null != formats[i]) // 数据格式
					if ("date".equals(formats[i])) {// 日期格式
						fv = myDateHandle
								.MyStringToISODateString(fv.toString());
					}
				if ("time".equals(formats[i])) { // 时间格式
					fv = myDateHandle
							.MyStringToISODateTimeString(fv.toString());
				}
				jobj.put(fieldRet[i], fv);
			}
			return jobj.toString();
		} catch (Exception e) {
		}
		return null;
	}

	public void up(String entityName, String colName, Object id,
			String nullException) throws Exception {
		upOrDown(entityName, colName, id, nullException, true);
	}

	public void down(String entityName, String colName, Object id,
			String nullException) throws Exception {
		upOrDown(entityName, colName, id, nullException, false);
	}

	private void upOrDown(String entityName, String colName, Object id,
			String nullException, boolean upOrDown) throws Exception {
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		Object o = dao.findById(id);
		if (null == o)
			throw new ServiceException(nullException);
		String rela;
		String rule;
		if (upOrDown) {
			rela = ">";
			rule = "asc";
		} else {
			rela = "<";
			rule = "desc";
		}
		Class cla = Class.forName("dao.pojo." + entityName);
		String temp = colName.substring(0, 1).toUpperCase()
				+ colName.substring(1);
		Method getMethod = cla.getMethod("get" + temp);
		Method setMethod = cla.getMethod("set" + temp, Integer.class);
		Integer sortOrder = (Integer) getMethod.invoke(o, null);
		if (null == sortOrder)
			sortOrder = 0;
		List<Object> oL = dao.findByPropertiesRule(new String[] { colName },
				new Object[] { sortOrder }, new String[] { rela },
				" order by model." + colName + " " + rule, 0, 1);
		if (null != oL && !oL.isEmpty()) {
			Object o_temp = oL.get(0);
			Integer sortOrder_temp = (Integer) getMethod.invoke(o_temp, null);
			if (null == sortOrder_temp)
				sortOrder_temp = 0;
			setMethod.invoke(o, sortOrder_temp);
			setMethod.invoke(o_temp, sortOrder);
			dao.update(o);
			dao.update(o_temp);
		}
	}

	public void top(String entityName, String colName, Object id,
			String nullException) throws Exception {
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		Object o = dao.findById(id);
		if (null == o)
			throw new ServiceException(nullException);
		Class cla = Class.forName("dao.pojo." + entityName);
		String temp = colName.substring(0, 1).toUpperCase()
				+ colName.substring(1);
		Method getMethod = cla.getMethod("get" + temp);
		Method setMethod = cla.getMethod("set" + temp, Integer.class);
		List<Object> oL = dao.findByPropertiesRule(null, null, null,
				" order by model." + colName + " desc", 0, 1);
		if (null != oL && !oL.isEmpty()) {
			Object o_temp = oL.get(0);
			Integer sortOrder_temp = (Integer) getMethod.invoke(o_temp, null);
			if (null == sortOrder_temp)
				sortOrder_temp = 0;
			setMethod.invoke(o, sortOrder_temp + 1);
			dao.update(o);
		}
	}

	public void setTrue(String entityName, String colName, Object id,
			String nullException) throws Exception {
		setTrueOrFalse(entityName, colName, id, nullException, true);
	}

	public void setFalse(String entityName, String colName, Object id,
			String nullException) throws Exception {
		setTrueOrFalse(entityName, colName, id, nullException, false);
	}

	public void setTrueOrFalse(String entityName, String colName, Object id,
			String nullException, boolean trueOrFalse) throws Exception {
		IBaseDAO dao = (IBaseDAO) SpringContextUtil.getBean(entityName + "DAO");
		Object o = dao.findById(id);
		if (null == o)
			throw new ServiceException(nullException);
		Class cla = Class.forName("dao.pojo." + entityName);
		String temp = colName.substring(0, 1).toUpperCase()
				+ colName.substring(1);
		Method setMethod = cla.getMethod("set" + temp, Boolean.class);
		setMethod.invoke(o, trueOrFalse);
		dao.update(o);
	}

}
